"""
# @Time : 2020/6/8 0008 23:09 
# @Author : xx
# @File : preprocess.py 
# @Software: PyCharm
"""
import numpy as np
from PIL import Image
from concurrent.futures import ThreadPoolExecutor


def single_img_process(img):
    im = img.convert('L')
    scale = im.size[1] * 1.0 / 32
    w = im.size[0] / scale
    w = int(w)

    im = im.resize((w, 32), Image.ANTIALIAS)
    img = np.array(im).astype(np.float32) / 255.0 - 0.5
    img = img.reshape((32, w, 1))
    return img


def pad_img(img, len, value):
    out = np.ones(shape=(32, len, 1), dtype=np.float32) * value
    out[:, :img.shape[1], :] = img
    return out


def process_imgs(imgs):
    tmp = []
    with ThreadPoolExecutor() as executor:
        for img in executor.map(single_img_process, imgs):
            tmp.append(img)

    max_len = max(max([img.shape[1] for img in tmp]), 640)

    output = []
    with ThreadPoolExecutor() as executor:
        for img in executor.map(lambda img: pad_img(img, max_len, 0.5), tmp):
            output.append(img)

    return np.array(output)
